<template>
  <div class="template-management">
    <!-- 工具栏 -->
    <div class="toolbar">
      <el-input 
        v-model="keyword" 
        placeholder="请输入模板名称" 
        style="width: 300px; margin-right: 10px;" 
        @keyup.enter="getTemplateList"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="getTemplateList" size="medium">搜索</el-button>
      <el-button 
        type="primary" 
        @click="handleAddTemplate" 
        size="medium"
        :icon="Plus"
        style="margin-left: 10px;"
      >
        添加模板
      </el-button>
    </div>
    
    <!-- 表格部分 -->
    <div class="table-section">
      <div class="table-header">
        <h3>模板列表</h3>
        <div class="table-controls">
          <el-button
            size="small"
            @click="handleRefresh"
            :icon="Refresh"
            :loading="loading"
          >
            刷新
          </el-button>
        </div>
      </div>

      <div class="table-container">
        <el-table
          :data="templatesData"
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          :header-cell-style="{
            background: '#f8f9fa',
            color: '#333',
            fontWeight: '500',
            textAlign: 'center',
          }"
          :cell-style="{ textAlign: 'center' }"
        >
          <el-table-column 
            prop="id" 
            label="ID" 
            width="80" 
            align="center"
          />
          <el-table-column 
            prop="template_name" 
            label="模板名称" 
            min-width="200"
            align="center"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <div class="title-cell">
                <span>{{ row.template_name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column 
            prop="create_time" 
            label="创建时间" 
            width="180" 
            align="center"
          >
            <template #default="{ row }">
              <div class="time-cell">
                <el-icon><Clock /></el-icon>
                <span>{{ row.create_time }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column 
            label="操作" 
            width="200" 
            align="center"
            fixed="right"
          >
            <template #default="scope">
              <div class="action-buttons">
                <el-button size="small" @click="handleViewTemplate(scope.row)">
                  查看
                </el-button>
                <el-button size="small" type="primary" @click="handleEditTemplate(scope.row)">
                  编辑
                </el-button>
                <el-button size="small" type="danger" @click="handleDeleteTemplate(scope.row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-container" style="margin-top: 20px;">
      <div class="pagination-info">
        <span>共 {{ total }} 条记录，当前显示第 {{ (page - 1) * limit + 1 }} - {{ Math.min(page * limit, total) }} 条</span>
      </div>
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="limit"
        :page-sizes="[10, 20, 50, 100]"
        layout="sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        size="small"
      />
    </div>
    
    <!-- 添加/编辑模板对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="850px"
      destroy-on-close
    >
      <el-form :model="formData" label-width="80px">
        <el-form-item label="模板名称">
          <el-input v-model="formData.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板内容">
          <!-- WangEditor富文本编辑器 -->
                <div class="editor-wrapper">
                  <Toolbar
                     style="border-bottom: 1px solid #ccc"
                     :editor="editorRef"
                     :mode="mode"
                     :defaultConfig="toolbarConfig"
                   />
                  <Editor
                    style="height: 530px; overflow-y: hidden;"
                    v-model="formData.templateContent"
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    @onCreated="handleEditorCreated"
                    @onChange="handleEditorChange"
                  />
                </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSaveTemplate">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 查看模板对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="查看模板"
      width="850px"
    >
      <div class="view-content">
        <h3>{{ currentTemplate.templateName }}</h3>
        <div class="content-display" v-html="currentTemplate.templateContent"></div>
      </div>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue';
import { ElMessage, ElMessageBox, ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus';
import { Plus, Search, Refresh, Clock } from '@element-plus/icons-vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { Boot } from '@wangeditor/editor';
import { resultReportTemplateAPI } from '../api/modules/resultReportTemplate.js';

// 模板变量列表 - 设置默认值，确保在网页模式下也能正常工作
const templateVars = ref([
  { label: '设备名称', key: 'deviceName' },
  { label: '开始时间', key: 'startTime' },
  { label: '结束时间', key: 'endTime' },
  { label: '检测结果', key: 'result' },
  { label: '检测人员', key: 'operator' },
  { label: '备注', key: 'remark' }
]);

// 尝试从electron中获取已加载的配置
onMounted(() => {
  try {
    // 在Electron环境中，通过window.electron获取已加载的配置
    console.log('window.electron:', window.electron);
    if (window.electron && window.electron.electronConfig && window.electron.electronConfig.APP_CONFIG && window.electron.electronConfig.APP_CONFIG.TEMPLATE_VARS) {
      templateVars.value = window.electron.electronConfig.APP_CONFIG.TEMPLATE_VARS;
      console.log('从Electron获取的templateVars:', templateVars.value);
    } else {
      console.log('使用默认模板变量列表:', templateVars.value);
    }
  } catch (error) {
    console.log('无法从electron获取配置，使用默认变量列表:', templateVars.value);
  }
  
  // 组件挂载时获取模板列表
  getTemplateList();
});

// 自定义变量菜单类 - 使用纯JavaScript语法实现
class VariableMenu {
  constructor() {
    this.title = '插入变量';
    this.tag = 'button';
    this.iconSvg = '<svg width="18" height="18" viewBox="0 0 18 18"><rect x="3" y="3" width="12" height="12" rx="2" ry="2" stroke="currentColor" fill="none" stroke-width="1.5"/><path d="M6 7.5h6M6 10.5h9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>';
    this.showModal = true;
  }
  
  // 获取菜单执行时的 value，用不到则返回空字符串
  getValue(editor) {
    return '';
  }
  
  // 菜单是否需要激活，用不到则返回 false
  isActive(editor) {
    return false;
  }
  
  // 菜单是否需要禁用，用不到则返回 false
  isDisabled(editor) {
    return false;
  }
  
  // 点击菜单时触发的函数
  exec(editor, value) {
    if (this.isDisabled(editor)) return;
    // 触发变量选择菜单
    if (window._showVariableMenu) {
      window._showVariableMenu();
    }
  }
}

// 注册自定义菜单 - 使用全局变量确保只注册一次
if (!window._variableMenuRegistered) {
  Boot.registerMenu({ key: 'insertVariable', factory() { return new VariableMenu(); } });
  window._variableMenuRegistered = true;
}

// 分页相关数据
const page = ref(1);
const limit = ref(10);
const total = ref(0);
const keyword = ref('');
const templatesData = ref([]);
const loading = ref(false); // 添加loading状态

// 对话框相关
const dialogVisible = ref(false);
const viewDialogVisible = ref(false);
const dialogTitle = ref('添加模板');
const currentTemplate = ref({});

// 表单数据
const formData = reactive({
  id: '',
  templateName: '',
  templateContent: ''
});

// 获取模板列表
const getTemplateList = async () => {
  loading.value = true;
  try {
    const response = await resultReportTemplateAPI.getResultReportTemplateList({
      pageNum: page.value,
      pageSize: limit.value,
      keyword: keyword.value
    });
    
    if (response && response.code === 0) {
      templatesData.value = response.data.list || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error('获取模板列表失败');
      templatesData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取模板列表出错:', error);
    ElMessage.error('获取模板列表失败');
  } finally {
    loading.value = false;
  }
};

// 刷新模板列表
const handleRefresh = () => {
  getTemplateList();
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  limit.value = newSize;
  getTemplateList();
};

// 处理当前页变化
const handleCurrentChange = (newCurrent) => {
  page.value = newCurrent;
  getTemplateList();
};

// WangEditor 配置
const mode = 'default';
const editorRef = ref(null);
// 工具栏配置 - 按照官方文档格式配置
  const toolbarConfig = {
    toolbarKeys: [
      'header1', 'header2', 'header3', '|',
      'bold', 'italic', 'underline', 'through', '|',
      'fontSize', 'fontFamily','lineHeight', '|',
      'color', 'bgColor', '|',
      'bulletedList', 'numberedList', '|',
      'justifyLeft', 'justifyCenter', 'justifyRight', '|',
      'indent', 'delIndent', '|',
      'insertVariable', '|',
      'uploadImage', '|',
      'undo', 'redo'
    ]
  };
  
  // 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  toolbarConfig: toolbarConfig,
  // 配置编辑器保留HTML格式
  htmlFilter: false, // 关闭HTML过滤
  pasteFilterStyle: false, // 保留粘贴的样式
  pasteIgnoreImg: true, // 允许粘贴图片
  // 自定义粘贴处理，确保HTML格式正确保留
  onPaste: (editor, event) => {
    // 允许默认粘贴行为
    return false;
  },
  // 确保编辑器能正确处理HTML内容
  sanitize: false, // 不进行HTML清理，保留所有标签和属性
  withCredentials: false, // 跨域请求设置
  // 增加自定义样式配置
  styles: {
    // 编辑器内容区域的全局样式
    content: {
      // 保留默认样式的同时允许自定义样式
    }
  },
  // 图片上传配置
  MENU_CONF: {
      uploadImage: {
        // 配置本地图片上传
        server: '', // 空字符串表示使用默认的 base64 编码
        timeout: 5000, // 5秒超时
        fieldName: 'file',
        meta: {}, // 自定义上传参数
        metaWithUrl: false, // meta 是否拼接到 url 上
        headers: {}, // 自定义请求头
        withCredentials: false, // 是否带 cookie
        // 自定义上传行为
        async customUpload(file, insertFn) {
          // 使用 FileReader 将图片转换为 base64
          const reader = new FileReader();
          reader.onload = function(e) {
            // 插入图片
            insertFn(e.target.result, file.name, file.size);
          };
          reader.readAsDataURL(file);
        }
      }
    }
  };

// 监听formData变化，当编辑不同模板时确保内容正确更新
let isEditorInitialized = false;

watch(() => formData.templateContent, (newContent) => {
  if (editorRef.value && newContent && isEditorInitialized) {
    // 确保编辑器内容与formData同步
    editorRef.value.setHtml(newContent);
  }
}, { immediate: false });

// 编辑器创建完成
  const handleEditorCreated = (editor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
    isEditorInitialized = true;
    // 确保编辑器内容样式正确
    if (formData.templateContent) {
      editor.setHtml(formData.templateContent);
    }
  };
  
  // 在组件初始化时将showVariableMenu绑定到window对象
  window._showVariableMenu = () => showVariableMenu();
  
  // 显示变量选择菜单
  const showVariableMenu = () => {
    // 找到工具栏中的变量按钮元素
    const variableBtn = document.querySelector('.w-e-toolbar [data-menu-key="insertVariable"]');
    if (variableBtn) {
      // 获取按钮位置，用于定位下拉菜单
      const rect = variableBtn.getBoundingClientRect();
      
      // 创建临时的下拉菜单元素
      let dropdown = document.getElementById('variable-dropdown-menu');
      if (!dropdown) {
        dropdown = document.createElement('div');
        dropdown.id = 'variable-dropdown-menu';
        dropdown.className = 'variable-dropdown';
        dropdown.style.cssText = `
          position: fixed;
          background: white;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
          z-index: 9999;
          max-height: 300px;
          overflow-y: auto;
          min-width: 150px;
        `;
        
        // 添加变量选项
        templateVars.value.forEach(varItem => {
          const item = document.createElement('div');
          item.className = 'variable-item';
          item.textContent = varItem.label;
          item.style.cssText = `
            padding: 8px 12px;
            cursor: pointer;
            white-space: nowrap;
          `;
          item.onmouseenter = () => {
            item.style.backgroundColor = '#f5f7fa';
          };
          item.onmouseleave = () => {
            item.style.backgroundColor = 'transparent';
          };
          item.onclick = () => {
            insertVariable(varItem.key);
            document.body.removeChild(dropdown);
          };
          dropdown.appendChild(item);
        });
        
        document.body.appendChild(dropdown);
      }
      
      // 定位下拉菜单
      dropdown.style.top = `${rect.bottom + window.scrollY + 5}px`;
      dropdown.style.left = `${rect.left + window.scrollX}px`;
      
      // 点击外部关闭菜单
      const handleClickOutside = (e) => {
        if (!dropdown.contains(e.target) && e.target !== variableBtn) {
          if (document.body.contains(dropdown)) {
            document.body.removeChild(dropdown);
          }
          document.removeEventListener('click', handleClickOutside);
        }
      };
      
      setTimeout(() => {
        document.addEventListener('click', handleClickOutside);
      }, 10);
    }
  };
  
  // 插入变量到编辑器
  const insertVariable = (variableKey) => {
    if (editorRef.value) {
      // 确保编辑器焦点，然后插入文本
      editorRef.value.focus();
      // 插入变量，格式为 {变量名}
      editorRef.value.insertText(`{${variableKey}}`);
    }
  };

  // 处理编辑器内容变化
const handleEditorChange = (editor) => {
  // 直接设置HTML内容，保留所有样式
  formData.templateContent = editor.getHtml();
};



// 添加模板
const handleAddTemplate = () => {
  dialogTitle.value = '添加模板';
  formData.id = '';
  formData.templateName = '';
  formData.templateContent = '';
  dialogVisible.value = true;
};

// 编辑模板
const handleEditTemplate = (template) => {
  dialogTitle.value = '编辑模板';
  formData.id = template.id;
  formData.templateName = template.template_name;
  formData.templateContent = template.template_content;
  dialogVisible.value = true;
};

// 查看模板
const handleViewTemplate = (template) => {
  // 检查字段存在性，防止字段名不一致导致的显示问题
  console.log('查看模板数据:', template);
  currentTemplate.value = {
    templateName: template.template_name,
    templateContent: template.template_content
  };
  viewDialogVisible.value = true;
};

// 删除模板
const handleDeleteTemplate = async (template) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除模板「${template.template_name}」吗？`,    
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const response = await resultReportTemplateAPI.deleteResultReportTemplate(template.id);
    
    if (response && response.code === 0) {
      ElMessage.success('删除模板成功');
      getTemplateList(); // 重新获取模板列表
    } else {
      ElMessage.error('删除模板失败：' + (response.message || '未知错误'));
    }
  } catch (error) {
    if (error === 'cancel') return; // 用户取消操作
    console.error('删除模板出错:', error);
    ElMessage.error('删除模板失败');
  }
};

// 保存模板
const handleSaveTemplate = async () => {
  if (!formData.templateName || formData.templateName.trim() === '') {
    ElMessage.warning('请输入模板名称');
    return;
  }
  
  try {
    let response;
    const data = {
      templateName: formData.templateName,
      templateContent: formData.templateContent
    };
    
    if (formData.id) {
      // 更新模板
      response = await resultReportTemplateAPI.updateResultReportTemplate(formData.id, data);
    } else {
      // 添加模板
      response = await resultReportTemplateAPI.addResultReportTemplate(data);
    }
    
    if (response && response.code === 0) {
      ElMessage.success(formData.id ? '更新模板成功' : '添加模板成功');
      dialogVisible.value = false;
      getTemplateList(); // 重新获取模板列表
    } else {
      ElMessage.error((formData.id ? '更新' : '添加') + '模板失败：' + (response.message || '未知错误'));
    }
  } catch (error) {
    console.error((formData.id ? '更新' : '添加') + '模板出错:', error);
    ElMessage.error((formData.id ? '更新' : '添加') + '模板失败');
  }
};

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false;
  formData.id = '';
  formData.templateName = '';
  formData.templateContent = '';
};

// 暴露变量选择菜单给自定义按钮使用
window._showVariableMenu = () => {
  // 创建变量选择弹窗
  ElMessageBox.confirm(
    `
    <div style="max-height: 300px; overflow-y: auto; padding: 10px;">
      <h3 style="margin-bottom: 15px;">选择要插入的变量</h3>
      <div class="variable-list">
        ${templateVars.value.map(v => 
          `<button type="button" 
            style="margin: 5px; padding: 5px 10px; background: #f0f0f0; border: 1px solid #ddd; border-radius: 4px; cursor: pointer;"
            onclick="window._insertVariable({key: '${v.key}'}); document.querySelector('.el-message-box__headerbtn').click();"
          >
            ${v.label} ({${v.key}})
          </button>`
        ).join('')}
      </div>
    </div>
    `,
    '插入变量',
    {
      confirmButtonText: '取消',
      showCancelButton: false,
      dangerouslyUseHTMLString: true,
      showClose: true
    }
  ).catch(() => {});
};

// 组件卸载时清理
onBeforeUnmount(() => {
  // 销毁 editor 实例，重要！
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
  
  // 清理全局方法
  if (window._showVariableMenu) {
    delete window._showVariableMenu;
  }
  if (window._insertVariable) {
    delete window._insertVariable;
  }
});
</script>

<style scoped>
.template-management {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.table-controls {
  display: flex;
  gap: 10px;
}

.table-container {
  flex: 1;
  overflow: auto;
  min-height: 0;
}

.title-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 5px;
  justify-content: center;
}

.action-buttons {
  display: flex;
  gap: 5px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  flex-shrink: 0;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* WangEditor编辑器样式 */
.editor-wrapper {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

/* 覆盖WangEditor默认样式 */
:deep(.w-e-toolbar) {
  padding: 0 10px;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.w-e-text-container) {
  min-height: 300px;
  border: none;
}

.view-content {
  padding: 20px;
  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 20px;
  }
}

.content-display {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #ffffff;
  min-height: 400px;
  max-height: 600px;
  overflow-y: auto;
  line-height: 1.8;
  font-size: 14px;
  color: #333;
  margin-top: 20px;
  
  /* 确保内部内容正确渲染 */
  img {
    max-width: 100%;
    height: auto;
  }
  table {
    width: 100%;
    border-collapse: collapse;
    margin: 10px 0;
  }
  table, th, td {
    border: 1px solid #ddd;
  }
  th, td {
    padding: 8px;
    text-align: left;
  }
  th {
    background-color: #f5f7fa;
  }
}
</style>